﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DrillOnline.Services;
using DrillOnline.Services.Scenarios;


namespace DrillOnline.Controllers
{

    public class HomeController : _BaseController
    {
        //GET:			/Home/SessionInfo			session info for banner,...
        public ActionResult SessionInfo() {
            var cs = GetCurrentSession();

            var m = cs;
            return PartialView(m);
        }

        public ActionResult VT(string id)
        {
            return View(id);
            //System.Web.Security.RolePrincipal user=User;
            //System.Web.Security.FormsIdentity identity = user.IsInRole;


        }

        JsonResult MyJson(object data) {
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        SortedList<string, string> DB_User;
        public HomeController() {
            DB_User = new SortedList<string, string>();
            DB_User.Add("kevin.geng", "GroupA");
            DB_User.Add("mac", "GroupB");
        }
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult Admin() {
            return View(string.Empty);
        }
        public ActionResult LoadScenarios(DateTime storytime,int timerate,int skiphead=0) {
            if (Request.Files.Count == 0 || Request.Files[0].ContentLength==0)
            {
                ModelState.AddModelError("file","No srt file.");
                return View("Admin");
            }



            //测试时只支持一个剧情，name is default

            DrillScenarios ds = null;
            if (!ScenariosHost.Instance.Sessions.ContainsKey("default"))
            {
                ds = new DrillScenarios();

                ScenariosHost.Instance.Sessions.Add("default", ds);
            }
            else {
                ds = ScenariosHost.Instance.Sessions["default"] as DrillScenarios;
            }

            ds.SessionKey = "default";
            ds.SessionName="测试放映";
            ds.ScenariosName=System.IO.Path.GetFileNameWithoutExtension( Request.Files[0].FileName);

            ds.SceneList = __TEST_CREATE_RANDOM_SCRIPT();
            
            //以后角色组/角色就已经定义在剧情里了。有了剧情就有了角色组了
            //测试时，有两个组 GroupA B
            ds.ActorGroups = new List<ActorGroup>(new ActorGroup[] {
                new ActorGroup(){ GroupKey="GroupA"},
                new ActorGroup(){ GroupKey="GroupB"}});
            //剧情的起始年代也就已经定了
            ds.Timeline.StoryBaseTime = storytime;
            ds.Timeline.Config_PlayingTimeRate = timerate;
            ds.Timeline.Config_TickerInterval =500;

            return View("Admin");

        }
        List<DrillScene> __TEST_CREATE_RANDOM_SCRIPT()
        {
            List<DrillScene> sl = new List<DrillScene>();
            //Random r = new Random();
            //int st = 0;
            //for (int i = 0; i < 200; i++)
            //{
            //    st += r.Next(0, 240);
            //    sl.Add(new DrillScene() { SecOffset = st, Title = "Title of " + i.ToString(), Content = "Full content of " + i.ToString() });
            //}
            string[] actors={"GroupA","GroupB"};
            using (var sr = new System.IO.StreamReader(Request.Files[0].InputStream,System.Text.Encoding.UTF8))
            {
                foreach (var item in  sr.ReadToEnd().Split(new string[] { "\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    try
                    {
                        var ls = item.Split(new string[] { "\r\n" }, 3, StringSplitOptions.RemoveEmptyEntries);
                        sl.Add(new DrillScene()
                        {
                            Offset = (int)TimeSpan.Parse(ls[1].Split('-')[0].Replace(',', '.').Trim()).TotalSeconds,
                            Groups = actors,
                            Title = ls[0] + "  " + ls[2]
                            //load more attributes
                        });

                    }
                    catch { }
                }
            }
            return sl;
        }

        [HttpGet]
        public ActionResult Start(string Scenarios="default")
        {
            var scenarioobj = ScenariosHost.Instance.Sessions[Scenarios];
            if (null == scenarioobj) return MyJson(false);
            scenarioobj.Timeline.Start();
            return View("Admin"); //return MyJson(true);
        }

        [HttpGet]
        public ActionResult Pause(string Scenarios = "default")
        {
            var scenarioobj = ScenariosHost.Instance.Sessions[Scenarios];
            if (null == scenarioobj) return MyJson(false);
            scenarioobj.Timeline.Pause();
            return View("Admin"); //return MyJson(true);
        }

        [HttpGet]
        public ActionResult Stop(string Scenarios = "default")
        {
            var scenarioobj = ScenariosHost.Instance.Sessions[Scenarios];
            if (null == scenarioobj) return MyJson(false);
            scenarioobj.Timeline.Stop();
            return View("Admin"); //return MyJson(true);
        }

        [HttpGet]
        public ActionResult FetchEvents(string SecOffset="0") {
            int so = 0;
            int.TryParse(SecOffset, out so);
            if (!ScenariosHost.Instance.Sessions.ContainsKey("default")) {
                return MyJson(new
                {
                    PlayingSecOffset = 0,
                    SceneList = new string[0]{}
                });
            }
            var scenario = ScenariosHost.Instance.Sessions["default"] as DrillScenarios;
            var el = scenario.SceneList.Where(v => v.Offset > so && v.Offset <= scenario.Timeline.PlayingOffset)
                .ToArray();
            return MyJson(new
            { 
                PlayingSecOffset=scenario.Timeline.PlayingOffset ,
                SceneList=el
            });
        }
    }
}
